<template>
<div>
  <el-dialog :title="title" :visible.sync="$store.state.dialogFormVisible" :width="boxWidth" :center="true" @close="cancelLogin" @open="openReset">
  <el-form :model="formlogin" v-show="showlogin" ref="formlogin">
    <el-input v-model="formlogin.name" size="medium" placeholder="用户名/邮箱"></el-input>
    <el-input v-model="formlogin.password" size="medium" placeholder="请输入密码" :show-password="true"></el-input>
  </el-form>
  <el-form v-model="formRegister" v-show="showregister">
  <!--  <el-input v-model="formRegister.name" size="medium" placeholder="用户名"></el-input>-->
    <el-input v-model="formRegister.email" size="medium" placeholder="邮箱"></el-input>
    <el-row :gutter="20">
      <el-col :span="14"><el-input size="medium" placeholder="输入验证码" v-model="formRegister.authCode"></el-input></el-col>
      <el-col :span="8"><el-button size="medium" @click="resend" :disabled="isdisabled">{{checkbtn}}</el-button></el-col>
    </el-row>
    <el-input v-model="formRegister.newPassword" size="medium" placeholder="密码" :show-password="true"></el-input>
    <el-input v-model="formRegister.rePassword" size="medium" placeholder="确认密码" :show-password="true"></el-input>
  </el-form>
  <el-form v-model="formPsw" v-show="showforgetpsw">
    <el-input v-model="formPsw.email" size="medium" placeholder="邮箱"></el-input>
    <el-row :gutter="20">
      <el-col :span="14"><el-input size="medium" placeholder="输入验证码" v-model="formPsw.authCode"></el-input></el-col>
      <el-col :span="8"><el-button size="medium" @click="resend" :disabled="isdisabled">{{checkbtn}}</el-button></el-col>
    </el-row>
    <el-input v-model="formPsw.newPassword" size="medium" placeholder="修改密码" :show-password="true"></el-input>
    <el-input v-model="formPsw.rePassword" size="medium" placeholder="确认密码" :show-password="true"></el-input>
  </el-form>
  <el-divider></el-divider>
    <div class="lb-content-choose">
      <span @click="toRegister">前往注册</span>
      <span @click="toForgetpsw">忘记密码</span>
      <span @click="toLogin">前往登录</span>
    </div>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="sendLoginData">{{title}}</el-button>
  </div>
  </el-dialog>
</div>
</template>

<script>
import {request} from 'network/request'
export default{
  name: 'loginbox',
  data () {
    return {
      selectTab: 1,
      title: '登 录',
      showlogin: true,
      showregister: false,
      showforgetpsw: false,

      isdisabled: false,
      checkbtn: '获取验证码',

      formlogin: {
        name: '',
        password: ''
      },
      formRegister: {
          email: '',
          newPassword: '',
          rePassword: '',
          authCode: ''
      },
      formPsw: {
        email: '',
        newPassword: '',
        rePassword: '',
        authCode: ''
      },
      boxWidth: '350px'
    }
  },
  /**
   * 监听selectTab，切换时修改title的属性
   * **/
  watch:{
    selectTab:function () {
      if(this.selectTab === 1){
        this.title = '登 录'
      }
      else if(this.selectTab === 2){
        this.title = '注 册'
      }
      else if(this.selectTab === 3){
        this.title = '修改密码'
      }
    }
  },
  methods: {
    /* 点击取消登录 */
    cancelLogin() {
      //关闭登录框
      this.$store.commit('closeLobinBox')
    },

    /* 点击确定，保存数据登录 */
    sendLoginData() {
      if(this.selectTab === 1){
        this.userLogin()
      }
      if(this.selectTab === 2){
        this.userRegister()
      }
      if(this.selectTab === 3){
        this.updatePassword()
      }
    },

    userLogin(){
      //检查数据的合法性
      const name = this.formlogin.name;
      const password = this.formlogin.password;
      if(name == null || name === ''){
        this.$message.error('用户名不能为空');
        return;
      }
      if(password == null || password === ''){
        this.$message.error('密码不能为空');
        return;
      }
      //验证邮箱是否符合格式
      var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if(!reg.test(name)){
        this.$message.error('邮箱格式不对');
        return;
      }
      //验证密码是否大于6位
      if(password.length < 6){
        this.$message.error('密码不对');
        return;
      }

      //发送登录请求
      request({
        url:'/blog/login',
        method: 'POST',
        params: { userName: name,password: password}
      }).then(response => {
        if(response.code === 20000){
          this.$message({
            message: '登录成功',
            type: 'success'
          });
          //将用户信息放入sessionStorage
          sessionStorage.setItem('userDetail', window.JSON.stringify(response.data))
          //将用户信息放入vuex
          this.$store.dispatch('setUser', response.data)
          //关闭登录框
          this.$store.commit('closeLobinBox')
        }else{
          this.$message.error(response.message);
        }
      }).catch(error => {
                this.$message.error('登录失败，请联系管理员');
              }
      )
    },
    /**
     * 用户登录
     * */
    userRegister() {
      //数据合法性检查
      //检查数据的合法性
      const email = this.formRegister.email;
      const newPassword = this.formRegister.newPassword;
      const rePassword = this.formRegister.rePassword;
      const authCode = this.formRegister.authCode;

      if(email == null || email === ''){
        this.$message.error('邮箱不能为空');
        return;
      }
      if(newPassword == null || newPassword === ''){
        this.$message.error('密码不能为空');
        return;
      }
      if(rePassword == null || rePassword === ''){
        this.$message.error('确认密码不能为空');
        return;
      }
      if(authCode == null || authCode === ''){
        this.$message.error('验证码不能为空');
        return;
       }

      //验证邮箱是否符合格式
      const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if(!reg.test(email)){
        this.$message.error('邮箱格式不合法');
        return;
      }
      //验证密码是否大于6位
      if(newPassword.length < 6){
        this.$message.error('密码必须大于6位');
        return;
      }

      //验证两次密码是否一样
      if(newPassword !== rePassword){
        this.$message.error('密码和确认密码不相同');
        return;
      }

      //发送登录请求
      request({
        url:'/blog/registerByEmail',
        method: 'POST',
        data: { userName: email,password: newPassword,authCode: authCode}
      }).then(response => {
        if(response.code === 20000){
          this.$message({
            message: '注册成功',
            type: 'success'
          });
          //关闭登录框
          this.$store.commit('closeLobinBox')
        }else{
          this.$message.error(response.message);
        }
      }).catch(error => {
                this.$message.error('注册失败，请联系管理员');
              }
      )

    },
    /**
     * 注册时获取验证码
     * */
    getAuthCode(email){
      request({
        url:'/blog/getAuthCode',
        method: 'POST',
        data:{
            email: email
        }
      }).then(response => {
        if(response.code === 20000){
          this.$message({
            message: '发送验证成功,时效为3分钟',
            type: 'success'
          });
        }else{
          this.$message.error(response.message);
        }
      }).catch(error => {
                this.$message.error('发送验证码失败');
              }
      )
    },

    /**
     * 修改密码
     * */
    updatePassword(){
      //验证数据的合法性
      const email = this.formPsw.email;
      const newPassword = this.formPsw.newPassword;
      const rePassword = this.formPsw.rePassword;
      const authCode = this.formPsw.authCode;

      if(email == null || email === ''){
        this.$message.error('邮箱不能为空');
        return;
      }

      if(newPassword == null || newPassword === ''){
        this.$message.error('密码不能为空');
        return;
      }

      if(rePassword == null || rePassword === ''){
        this.$message.error('确认密码不能为空');
        return;
      }

      if(authCode == null || authCode === ''){
        this.$message.error('验证码不能为空');
        return;
      }

      //验证密码是否大于6位
      if(newPassword.length < 6){
        this.$message.error('密码必须大于6位');
        return;
      }

      //验证两次密码是否一样
      if(newPassword !== rePassword){
        this.$message.error('密码和确认密码不相同');
        return;
      }

      //发送更改密码的请求
      request({
        url:'/blog/updatePassword',
        method:'POST',
        data:{
          email: email,
          password: newPassword,
          authCode: authCode
        }
      }).then(response => {
        if(response.code === 20000){
          this.$message({
            message: '更改密码成功，请重新登录',
            type: 'success'
          });
          //关闭登录框
          this.$store.commit('closeLobinBox')
        }else{
          this.$message.error(response.message);
        }
      }).catch(error => {
                this.$message.error('更改密码失败');
              }
      )
    },

    /* 打开时初始化 */
    openReset() {
      this.formlogin = {name: '', password: ''}
      this.formRegister = {email: '', newPassword: '', rePassword: ''}
      this.formPsw = {email: '', newPassword: '', rePassword: ''}
    },

    /* 点击获取验证码后倒计时60秒 */
    resend() {
        //检查邮箱是否以及填写
       let email;
       if(this.selectTab === 2){
         email = this.formRegister.email;
       }
       else if(this.selectTab === 3){
         email = this.formPsw.email;
       }
       if(email == null || email === ''){
           this.$message.error('邮箱不能为空');
           return;
       }
       //检查邮箱的合法性
       const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
       if(!reg.test(email)){
           this.$message.error('邮箱格式不合法，请重新输入');
           return;
       }
      this.isdisabled = true
      let countdown = 60
      //发送到邮箱的验证码
      this.getAuthCode(email);
      setTimeout(() => {
        this.setTime(countdown)
      }, 1000)
    },
    //启动倒计时
    setTime(countdown) {
      clearTimeout(timer)
      if (countdown === 0) {
        this.isdisabled = false
        this.checkbtn = '获取验证码'
        countdown = 60
        return false
      } else {
        this.checkbtn = `重新发送(${countdown})`
        countdown --
        console.log(countdown);
      }
      const timer = setTimeout(() => {
        this.setTime(countdown)
      }, 1000)
    },

    /* 切换登录注册忘记密码 */
    toLogin() {
      this.selectTab = 1
      this.showlogin = true
      this.showregister = false
      this.showforgetpsw = false
    },
    toRegister() {
      this.selectTab = 2
      this.showlogin = false
      this.showregister = true
      this.showforgetpsw = false
    },
    toForgetpsw() {
      this.selectTab = 3
      this.showlogin = false
      this.showregister = false
      this.showforgetpsw = true
    }
  }
}
</script>

<style scoped>
.el-input{
  margin: 5px;
}
.el-button{
  margin: 5px;
}
.lb-content-choose{
  display: flex;
  justify-content: center;
}
.lb-content-choose span{
  font-size: 12px;
  padding: 0 5px;
  color: #a1a1a1;
}
.lb-content-choose span:hover{
  color: #234dda;
  cursor: pointer;
}
</style>
